<template>
  <md-popover
    placement="right-start"
    :visible-arrow="false"
    width="160"
    trigger="click"
    v-model="visible"
  >
    <template #reference>
      <slot></slot>
    </template>

    <md-input
      autofocus
      class="bi-popover-input"
      ref="input"
      autosize
      v-model="innerValue"
    />

    <div class="action-button">
      <md-button
        size="small"
        class="bi-popover-input-button"
        @click="handleCancel"
        >取消</md-button
      >
      <md-button
        size="small"
        class="bi-popover-input-button"
        type="primary"
        @click="handleConfirm"
        >确认</md-button
      >
    </div>
  </md-popover>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue';
defineOptions({
  name: 'layout-popover-input',
});

const props = defineProps({
  value: String,
  onChange: Function,
});

const visible = ref(false);
const defaultValue = ref(false);
const innerValue = ref(false);

const input = ref(); //ref
watch(visible, (val) => {
  if (val) {
    nextTick(() => {
      input.value?.focus?.();
    });
  }
});

function handleCancel() {
  visible.value = false;
  innerValue.value = defaultValue.value;
}
function handleConfirm() {
  props.onChange?.(innerValue.value);
  visible.value = false;
}
</script>

<style lang="scss" scoped>
.action-button {
  margin-top: var(--md-spacing-3);
  text-align: right;
}

.confirm {
  margin-left: var(--md-spacing-3);
}
</style>
